<script lang="ts" setup>
import { h, ref, reactive } from 'vue'
import { NSpace, NDivider, NRadioGroup, NRadio, NButton, NModal, NTreeSelect, NForm, NGrid, NSelect, NFormItemGi, NInput, NCard, NDataTable, NPopconfirm, useNotification } from 'naive-ui'
import type { FormInst, FormRules, DataTableColumns } from 'naive-ui'
import { useUserStore } from '@/stores/userStore'
import { useDictStore } from '@/stores/dictStore'
import { useOrgStore } from '@/stores/orgStore'
import http from '@/tools/http'

const props = defineProps(["objId", "objType", "userDataAuthUpdate", "listDataAuth", "userDataAuth", "orgDataAuthList"])
const emits = defineEmits(["update:userDataAuth"])

const userStore = useUserStore()
const dictStore = useDictStore()
const orgStore = useOrgStore()

const notification = useNotification()

type RowData = {
    objId?: string
    objType?: string
    dataType?: string
    dataObjCode?: string
    dataScope?: string
}

const dataAuthTableColumns: DataTableColumns<RowData> = [
    {
        title: "对象ID",
        key: "objId",
        width: 100
    }, {
        title: "对象类型",
        key: "objType",
        width: 100,
        render(rowData: RowData, rowIndex: number) {
            return dictStore.dictItem("OBJ_TYPE", rowData.objType)
        }
    }, {
        title: "数据类型",
        key: "dataType",
        width: 100,
        render(rowData: RowData, rowIndex: number) {
            return dictStore.dictItem("DATA_TYPE", rowData.dataType)
        }
    }, {
        title: "数据对象",
        key: "dataObjCode",
        width: 180,
        render(rowData: RowData, rowIndex: number) {
            return orgStore.getOrgName(rowData.dataObjCode)
        }
    }, {
        title: "数据范围",
        key: "dataScope",
        width: 150,
        render(rowData: RowData, rowIndex: number) {
            return dictStore.dictItem("DATA_SCOPE_ORG", rowData.dataScope)
        }
    }, {
        title: "操作",
        key: "actions",
        width: 132,
        fixed: "right",
        render(rowData: RowData, rowIndex: number) {
            return h(
                NSpace, null,
                () => [
                    h(
                        NButton,
                        {
                            size: "small",
                            disabled: !userStore.hasAuth('auth:edit'),
                            onclick: () => openEditDataAuth(rowData, "1")
                        },
                        { default: () => "编辑" }
                    ),
                    h(
                        NPopconfirm,
                        {
                            onPositiveClick: (e: MouseEvent) => deleteDataAuth()
                        },
                        {
                            trigger: () => {
                                return h(
                                    NButton,
                                    {
                                        size: "small",
                                        disabled: !userStore.hasAuth('auth:edit'),
                                        onclick: () => openDeleteDataAuth(rowData)
                                    },
                                    { default: () => "删除" }
                                )
                            },
                            default: () => { return "确认删除？" }
                        }
                    )
                ]
            )
        }
    }
]

const visiable = ref<boolean>(false)
const title = ref<string>("")
const formRef = ref<FormInst | null>(null)
const formData = reactive<RowData>({
    objId: props.objId,
    objType: props.objType,
    dataType: "",
    dataObjCode: "",
    dataScope: ""
})

const formRules: FormRules = ({
    objId: {
        required: true,
        message: '请输入对象ID',
        trigger: ['input']
    },
    objType: {
        required: true,
        message: '请输入对象类型',
        trigger: ['input']
    },
    dataType: {
        required: true,
        message: '请输入数据类型',
        trigger: ['input']
    },
    dataObjCode: {
        required: true,
        message: '请选择数据对象',
        trigger: ['input']
    },
    dataScope: {
        required: true,
        message: '请选择数据范围',
        trigger: ['input']
    }
})

function userDataAuthUpdate(value: string) {
    const request = {
        objId: props.objId,
        objType: props.objType,
        dataType: "0",
        dataObjCode: props.objId,
        dataScope: value
    }
    http.post("/data/auth/maintain", request).then(({ data }) => {
        if (data.code === "0") {
            notification['success']({
                content: '数据权限更新成功',
                meta: `${data.msg}`,
                duration: 2500,
                keepAliveOnHover: true
            })
            props.listDataAuth()
            emits("update:userDataAuth", value)
        }
    })
}

function openAddDataAuth(dataType: string) {
    visiable.value = true
    title.value = `添加${dictStore.dictItem("DATA_TYPE", dataType)}数据权限`
    formData.objId = props.objId
    formData.objType = props.objType
    formData.dataType = dataType
    formData.dataObjCode = ""
    formData.dataScope = "0"
}

function openEditDataAuth(row: RowData, dataType: string) {
    visiable.value = true
    title.value = `编辑${dictStore.dictItem("DATA_TYPE", dataType)}数据权限`
    formData.objId = row.objId
    formData.objType = row.objType
    formData.dataType = row.dataType
    formData.dataObjCode = row.dataObjCode
    formData.dataScope = row.dataScope
}

function openDeleteDataAuth(row: RowData) {
    formData.objId = row.objId
    formData.objType = row.objType
    formData.dataType = row.dataType
    formData.dataObjCode = row.dataObjCode
    formData.dataScope = row.dataScope
}

function submit() {
    formRef.value?.validate((errors) => {
        if (!errors) {
            maintainDataAuth()
            visiable.value = false
        }
    })
}

function maintainDataAuth() {
    http.post("/data/auth/maintain", formData).then(({ data }) => {
        if (data.code === "0") {
            notification['success']({
                content: '数据权限更新成功',
                meta: `${data.msg}`,
                duration: 2500,
                keepAliveOnHover: true
            })
            props.listDataAuth()
        }
    })
}

function deleteDataAuth() {
    http.post("/data/auth/delete", formData).then(({ data }) => {
        if (data.code === "0") {
            notification['success']({
                content: '删除成功',
                meta: `${data.msg}`,
                duration: 2500,
                keepAliveOnHover: true
            })
            props.listDataAuth()
        }
    })
}
</script>
<template>
    <n-divider title-placement="left" style="height:25px;margin-top:0;">用户数据</n-divider>
    <div style="height:23px;">
        <n-radio-group :value="props.userDataAuth" :on-update-value="userDataAuthUpdate"
            :disabled="!userStore.hasAuth('auth:edit')" name="radiogroup">
            <n-space>
                <n-radio v-for="dict in dictStore.dict('USER_DATA_AUTH_SCOPE')" :key="dict.value" :value="dict.value">
                    {{ dict.label }}
                </n-radio>
            </n-space>
        </n-radio-group>
    </div>
    <n-divider title-placement="left" style="height:25px;">机构数据</n-divider>
    <div class="btn-group" style="margin-top:0px;margin-left:0;margin-right:0;padding-top:0px;padding-left:0;padding-right:0;">
        <n-button :disabled="!userStore.hasAuth('auth:edit')" attr-type="button" @click="openAddDataAuth('1')">新增</n-button>
    </div>
    <div class="data-table" style="top:192px;bottom:12px;margin-left:0;margin-right:0;">
        <n-data-table :scroll-x="762" :scrollbar-props="{ trigger: 'none' }" style="height:100%" flex-height
            :columns="dataAuthTableColumns" :data="props.orgDataAuthList" :bordered="false" />
    </div>
    <n-modal v-model:show="visiable">
        <n-card style="width: 650px" :title="title">
            <n-form :disabled="!userStore.hasAuth('auth:edit')" ref="formRef" :model="formData" :rules="formRules"
                label-width="78px" label-placement="left" require-mark-placement="left">
                <n-grid :cols="2" :x-gap="24">
                    <n-form-item-gi :span="1" label="对象ID" path="objId">
                        <n-input v-model:value="formData.objId" disabled placeholder="请输入对象ID" clearable />
                    </n-form-item-gi>
                    <n-form-item-gi :span="1" label="对象类型" path="objType">
                        <n-select v-model:value="formData.objType" disabled :options="dictStore.dict('OBJ_TYPE')" />
                    </n-form-item-gi>
                    <n-form-item-gi :span="1" label="数据类型" path="dataType">
                        <n-select v-model:value="formData.dataType" disabled :options="dictStore.dict('DATA_TYPE')" />
                    </n-form-item-gi>
                    <n-form-item-gi :span="1" label="数据对象" path="dataObjCode">
                        <n-tree-select v-model:value="formData.dataObjCode" :options="orgStore.orgInfoTree" default-value=""
                            placeholder="请选择数据对象" clearable />
                    </n-form-item-gi>
                    <n-form-item-gi :span="1" label="数据范围" path="dataScope">
                        <n-select v-model:value="formData.dataScope" placeholder="请选择数据范围"
                            :options="dictStore.dict('DATA_SCOPE_ORG')" />
                    </n-form-item-gi>
                </n-grid>
            </n-form>
            <template #footer>
                <n-space justify="end">
                    <n-button attr-type="button" @click="visiable = false">取消</n-button>
                    <n-button attr-type="button" @click="submit()">提交</n-button>
                </n-space>
            </template>
        </n-card>
    </n-modal>
</template>
<style scoped></style>